import React, { Component } from 'react'

export default class Test1 extends Component {
	state = {carName:'奔驰'}
	render() {
		return (
			<div>
				<h2>车名为：{this.state.carName}</h2>
				<button onClick={this.changeCar}>破产了，换车</button>
				<button id="btn">破产了，换车2</button>
			</div>
		)
	}

	//componentDidMount是由react生命周期钩子，所以其中setState执行更新是异步的
	componentDidMount(){
		const btn = document.getElementById('btn')
		btn.addEventListener('click',()=>{
			this.setState({carName:'奥迪'})
			console.log(this.state.carName)
		})
	}
	
	//changeCar是由react所控制的回调，所以changeCar中setState执行更新是异步的
	changeCar = ()=>{
		//定时器回调中setState更新状态的动作是同步的
		/* setTimeout(()=>{
			this.setState({carName:'奥拓'})
			console.log('setState调完了',this.state.carName) //奔驰？？  奥拓？？
		}) */
		Promise.resolve(900).then(
			response => {
				this.setState({carName:'奥拓'})
				console.log('setState调完了',this.state.carName) //奔驰？？  奥拓？？
			},
		)
	}
}
